package com.xiao.community.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
       <dependency>
              <groupId>com.aliyun.oss</groupId>
              <artifactId>aliyun-sdk-oss</artifactId>
              <version>3.8.0</version>
          </dependency>
 */
public class OSSFileUtil {

    private static String endpoint = "oss-cn-shanghai.aliyuncs.com";
    private static String accessKeyId = "LTAI5tQVprF9BspQGzLoJRtr";
    private static String accessKeySecret = "EIP2XpxgllsVdZnpXM9FuJpD3X6Dy9";
    private static String bucketName = "demobucker";

    //url上传路径
    public static String uploadFile(MultipartFile file) throws IOException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        //获取文件名称
        String filename = file.getOriginalFilename();
        //得到一个uuid随机的字符串
        String uuid = UUID.randomUUID().toString();
        //uuid和文件的后缀名称拼接得到一个新的文件名称
        // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String objectName = uuid+filename.substring(filename.lastIndexOf("."));
        String fileName = getFileName(format, objectName);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）

        PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, file.getInputStream());
        System.out.println(putObjectResult);
        //
//        https://demobucker.oss-cn-shanghai.aliyuncs.com/2021-08-26/ba97a752db244a0999ac4632f8aa2447b7f6ced9-daa5-4d78-8527-c258691cd898.mp4
//        https://demobucker.oss-cn-shanghai.aliyuncs.com/b7f6ced9-daa5-4d78-8527-c258691cd898.mp4
// 关闭OSSClient。
        ossClient.shutdown();

        return "https://"+bucketName+"."+endpoint+"/"+fileName;

    }
    private static String getFileName(String fileType, String ext) {
        //上传至oss的那个文件夹 通过filename来指定 生成规则 // www.liangye123.com/img/20200814/jdg.png
        if (StringUtils.isEmpty(fileType)) {
            fileType = "default";
        }
        //为了避免图片重名，使用UUID来命名图片
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //组合filename
        String filename = fileType + "/" + uuid + ext;
        return filename;
    }


}
